package edu.auctionmart

class Item {
	
	static belongsTo = Auction
	
	ItemCategory category
	String name
	String description
	List<Byte> image
	String isbn
	Float weight
	String dimension
	int quantity

    static constraints = {
		name(nullable: false)
		description(nullable: false)
		category(nullable: false)
		image(nullable: true)
		isbn (nullable: true, validator: {
			if (it == null)
				return true
			
			def pattern
			it = it.replaceAll("-", "")
			if (it.size() == 13) {
				pattern = ~/(?=.{13}$)97(?:8|9)\d\d\d\d\d\d\d\d\d\d$/
				if (!pattern.matcher(it).matches())
					return 'isbnError';
			}
			else if (it.size() == 10) {
				pattern = ~/(?=.{10}$)97(?:8|9)\d\d\d\d\d\d\d$/
				if (!pattern.matcher(it).matches())
					return 'isbnError';
			}
		})
		weight(nullable: true)
		dimension(nullable: true)
		quantity(min: 1, nullable: true)
    }
	
	@Override
	def beforeInsert() {
		if (isbn != null)
			isbn = isbn.replaceAll("-", "")
	}
	
	@Override
	def beforeUpdate() {
		if (isbn != null)
			isbn = isbn.replaceAll("-", "")
	}
	
	String toString() {
		"${name}"
	}
}
